package cn.wolfcode.wolfcodemall.controller.fore;

import cn.wolfcode.wolfcodemall.domain.User;
import cn.wolfcode.wolfcodemall.service.UserService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * 前台用户登录相关请求
 */
@Controller("foreLoginController")
public class LoginController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public String loginPage(){
        return "/fore/loginPage";
    }

    @RequestMapping("/doLogin")
    @ResponseBody
    public String doLogin(String username, String password, HttpSession session){
        JSONObject jsonObject = new JSONObject();
        try{
            User user = userService.login(username, password);
            //登录成功
            //将登录的对象存储到session中
            session.setAttribute("user",user);

            jsonObject.put("success",true);
        }catch (Exception e){
            //登录失败
            jsonObject.put("success",false);
        }
        return jsonObject.toJSONString();
    }
    //退出登录
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        //删除session中的登录对象
        session.removeAttribute("user");
        //跳转到主页面
        return "redirect:/";
    }

}
